package client.ui.view.panel.main;

import base.BaseValue;
import client.UserState;
import client.connect.HttpConnect;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Good;
import client.entity.Record;
import client.entity.Store;
import client.entity.User;
import client.ui.component.button.MaterialButton;
import client.ui.component.card.Card;
import client.ui.component.divider.Divider;
import client.ui.component.layout.VFlowLayout;
import client.ui.component.scroll.SmallMouseWheelListener;
import client.ui.util.MaterialBorder;
import client.ui.view.dialogview.AuctionDialog;
import client.ui.view.dialogview.RecordDialog;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialColors;
import client.ui.view.EditPage;
import client.ui.view.GoodsPage;
import client.ui.view.base.FrameBase;
import client.ui.view.base.PanelControl;
import client.ui.view.module.BoughtItem;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
  * @Description 个人数据面板
  * @author 孔明浩
  * @Date 2020/3/31
  */
public class MyDataPanel extends JPanel implements PanelControl,ActionListener {
    private ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    private List<Good> myItems = new ArrayList<>();
    private List<Record> boughtItems = new ArrayList<>();
    private double money = 0;
    private JPanel moneyPanel;
    private JPanel favorPanel;
    private JPanel myShopPanel;
    private JPanel boughtItemPanel;
    private JPanel boughtPanel;
    private JPanel myShopPanelItems;
    private CardLayout cardLayout = new CardLayout();
    public MyDataPanel(){
        super();
        PanelControl.panels.put("MyDataPanel",this);
        initial();
    }

    //初始化添加组件
    private void initial(){
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints gridBagConstraints;
        this.setLayout(gridBagLayout);

        //余额面板
        initMoneyPanel();
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        this.add(moneyPanel, gridBagConstraints);

        //收藏面板
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.weighty = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        initFavorPanel();
        this.add(favorPanel,gridBagConstraints);

        //买过的货面板
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.weightx = 1;
        gridBagConstraints.weighty = 0.2;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = GridBagConstraints.NORTH;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        initBoughtPanel();
        this.add(boughtPanel, gridBagConstraints);

        //我的店铺面板
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.weightx = 1;
        gridBagConstraints.weighty = 0.8;
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;

        gridBagConstraints.anchor = GridBagConstraints.CENTER;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        initMyShopPanel();
        this.add(myShopPanel, gridBagConstraints);
        if (UserState.getUser().getStoreId() == null){
            cardLayout.show(myShopPanel, "noShop");
        }
    }

    private void initMoneyPanel(){
        moneyPanel = new JPanel(new VFlowLayout());
        moneyPanel.setBorder(new EmptyBorder(24,48,24,48));
        JLabel moneyLeft = new JLabel("账户余额:");
        moneyLeft.setFont(ThisFont.BIG_FONT);
        JLabel money = new JLabel("$  " + this.money);
        money.setFont(ThisFont.BIG_FONT);
        money.setForeground(MaterialColors.COSMO_BLUE);
        MaterialButton charge = MaterialButton.BlueButton("充值",null);
        charge.addActionListener(this);
        charge.setActionCommand("charge");

        moneyPanel.add(moneyLeft, BorderLayout.NORTH);
        moneyPanel.add(money, BorderLayout.CENTER);
        moneyPanel.add(charge, BorderLayout.SOUTH);

        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ResponseEntity responseEntity = Controller.USER_CONTROL.getGold(UserState.getToken());
                //查询更新金钱
                //查询成功
                if (responseEntity.getCode() == 0){
                    MyDataPanel.this.money = Double.parseDouble(responseEntity.getData());
                    updatePanel("moneyPanel");
                }
            }
        });
    }

    private void initFavorPanel(){
        favorPanel = new JPanel(new VFlowLayout());
        favorPanel.setMinimumSize(new Dimension(250,200));
        JLabel favorLabel = new JLabel("我的收藏");
        favorLabel.setFont(ThisFont.BIG_BOLD_FONT);

        //嵌套滚动面板
        JPanel panel = new JPanel(new VFlowLayout());
        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setBorder(null);
        favorPanel.add(new Divider(MaterialColors.COSMO_BLUE));
        favorPanel.add(favorLabel);
        favorPanel.add(scrollPane);
    }

    private void initBoughtPanel(){
        boughtPanel = new JPanel(new BorderLayout());
        boughtPanel.setBorder(MaterialBorder.FOCUSED_LINE_BORDER);
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(new EmptyBorder(12,12,12,12));
        JLabel label = new JLabel("买过的货");
        label.setFont(ThisFont.BIG_BOLD_FONT);

        //我买过的商品
        boughtItemPanel = new JPanel(new FlowLayout());
        JScrollPane scrollPane = new JScrollPane(boughtItemPanel);
        scrollPane.setMinimumSize(new Dimension(200,120));
        scrollPane.addMouseWheelListener(new SmallMouseWheelListener(20,scrollPane.getHorizontalScrollBar()));
        scrollPane.setBorder(null);
        Record record = new Record();
        record.setGoodName("正在加载...");
        record.setAmount(Double.NaN);
        record.setCount(1);
        record.setBoughtTime(new Date());
        boughtItemPanel.add(new BoughtItem(record));

        topPanel.add(label, BorderLayout.WEST);
        topPanel.add(new Divider(MaterialColors.COSMO_BLUE), BorderLayout.SOUTH);
        boughtPanel.add(topPanel, BorderLayout.NORTH);
        boughtPanel.add(scrollPane, BorderLayout.CENTER);
    }

    private void initMyShopPanel(){
        myShopPanel = new JPanel(cardLayout);

        //有商铺的面板
        JPanel haveShop = new JPanel(new BorderLayout());
        haveShop.setBorder(new LineBorder(MaterialColors.COSMO_BLUE));
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(new EmptyBorder(12,12,12,12));
        JLabel label = new JLabel("我的店铺");
        label.setFont(ThisFont.BIG_BOLD_FONT);

        Box hBox = Box.createHorizontalBox();
        MaterialButton newItem = MaterialButton.BlueButton("新建商品", null);
        newItem.addActionListener(this);
        newItem.setActionCommand("newItem");

        MaterialButton record = MaterialButton.BlueButton("业绩", null);
        record.addActionListener(this);
        record.setActionCommand("record");

        //我的店铺中的商品
        myShopPanelItems = new JPanel(new FlowLayout());
        JScrollPane scrollPane = new JScrollPane(myShopPanelItems);
        scrollPane.setBorder(null);
        //不要更改添加组件的顺序，这很重要！后面index有用到
        hBox.add(newItem);
        hBox.add(record);

        topPanel.add(label, BorderLayout.WEST);
        topPanel.add(hBox, BorderLayout.EAST);

        haveShop.add(topPanel, BorderLayout.NORTH);
        haveShop.add(scrollPane, BorderLayout.CENTER);

        //无店铺的面板
        JPanel noShop = new JPanel(new BorderLayout());
        MaterialButton newShop = MaterialButton.BlueButton("创建商铺",null);
        newShop.addActionListener(this);
        newShop.setActionCommand("newShop");
        JLabel textLabel = new JLabel("创建商铺后可以进行商品的放置售出哦",SwingConstants.CENTER);
        textLabel.setForeground(MaterialColors.COSMO_BLUE);
        textLabel.setFont(ThisFont.BIG_FONT);
        noShop.add(newShop, BorderLayout.NORTH);
        noShop.add(textLabel, BorderLayout.CENTER);

        //顺序不可更改
        myShopPanel.add("noShop",noShop);
        myShopPanel.add("haveShop",haveShop);

        //启动网络线程更新我的商品列表
        getMyGoodList();
        updatePanel("boughtPanel");
    }

    /**
     * @Description 利用String字符串匹配更新面板,内部启动线程更新
     * @param object 这里传入String字符串匹配，支持myShopPanel,moneyPanel,favorPanel,boughtPanel
     * @author 孔明浩
     * @Date 2020/4/5
     */
    @Override
    public void updatePanel(Object object) {
        String str = (String) object;
        switch (str){
            //我的店铺面板
            case "myShopPanel":
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if (UserState.getUser().getStoreId() == null){
                            cardLayout.show(myShopPanel,"noShop");
                        } else {
                            cardLayout.show(myShopPanel, "haveShop");
                            myShopPanelItems.removeAll();
                            for (Good g:myItems){
                                List<String> urls = JSONObject.parseArray(g.getPic(), String.class);
                                String url = "";
                                try{
                                    url = urls.get(0);
                                } catch (Exception e){
                                    e.printStackTrace();
                                }
                                Card card = new Card(g.getGoodId(),url,g.getGoodName(),g.getPrice());
                                card.addMouseListener(new MouseAdapter() {
                                    @Override
                                    public void mouseClicked(MouseEvent e) {
                                        //商品展示界面
                                        JFrame page = new GoodsPage(g.getGoodName(),g);
                                        page.setVisible(true);
                                    }
                                });
                                JPopupMenu popupMenu = new JPopupMenu();
                                JMenuItem delete = new JMenuItem("删除");
                                JMenuItem edit = new JMenuItem("编辑");
                                JMenuItem auction = new JMenuItem("拍卖");
                                JMenuItem state = new JMenuItem(g.getStatus() == 0 ? "上架" : "下架");

                                popupMenu.add(delete);
                                popupMenu.add(edit);
                                popupMenu.add(auction);
                                popupMenu.add(state);
                                card.setComponentPopupMenu(popupMenu);

                                //自定义解析命令
                                delete.addActionListener(MyDataPanel.this);
                                delete.setActionCommand("delete" + g.getGoodId());
                                edit.addActionListener(MyDataPanel.this);
                                edit.setActionCommand("edit" + g.getGoodId());
                                auction.addActionListener(MyDataPanel.this);
                                auction.setActionCommand("auction" + g.getGoodId());
                                state.addActionListener(MyDataPanel.this);
                                state.setActionCommand("state" + g.getGoodId());


                                myShopPanelItems.add(card);
                            }
                            myShopPanelItems.validate();
                            myShopPanelItems.repaint();
                        }
                    }
                });
            case "moneyPanel":
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        ((JLabel)moneyPanel.getComponent(1)).setText("$  " + MyDataPanel.this.money);
                    }
                });
            case "boughtPanel":
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        boughtItemPanel.removeAll();
                        for (Record r : boughtItems){
                            BoughtItem item = new BoughtItem(r);
                            item.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    actionPerformed(
                                            new ActionEvent(item, ActionEvent.ACTION_PERFORMED, "page"+r.getGoodId())
                                    );
                                }
                            });
                            boughtItemPanel.add(item);
                        }
                        if (boughtItemPanel.getComponents().length == 0){
                            JLabel label = new JLabel("您还没买过商品<(￣︶￣)↗[GO!]");
                            label.setFont(ThisFont.MIDDLE_FONT);
                            boughtItemPanel.add(label);
                        }
                        boughtItemPanel.validate();
                        boughtItemPanel.repaint();
                    }
                });
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
        switch (e.getActionCommand()){
            case "newItem":
                JFrame editGood = new EditPage("新建商品");
                editGood.setVisible(true);
                break;
            case "newShop":
                int code = JOptionPane.showConfirmDialog(MyDataPanel.this,
                        "确定创建店铺","创建店铺",JOptionPane.YES_NO_CANCEL_OPTION);
                //判断确定回执
                if (code == JOptionPane.YES_OPTION){
                    singleThreadExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            ResponseEntity responseEntity = Controller.STORE_CONTROL.createStore(
                                    UserState.getToken(), UserState.getUsername(), null
                            );
                            //若创建成功则更新UserState
                            if (responseEntity.getCode() == 0){
                                myItems = Controller.STORE_CONTROL.getStoreGoods(UserState.getToken());
                                showMessage("创建成功");
                                User user = JSONObject.parseObject(
                                        Controller.USER_CONTROL.getUserInfo(UserState.getToken()).getData()
                                        , User.class);
                                UserState.setUser(user);
                                updatePanel("myShopPanel");
                            } else{
                                showMessage("创建失败");
                            }
                        }
                    });
                }
                break;
            case "charge":
                String str = JOptionPane.showInputDialog(MyDataPanel.this,"请输入充值金额");
                int num = 0;
                try{
                    num = Integer.parseInt(str);
                } catch (Exception ignored){}
                //保证不进行负数充值
                if (num < 0){
                    showMessage("充值失败,请不要输入负数");
                    return;
                }
                int finalNum = num;
                singleThreadExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        ResponseEntity responseEntity = Controller.USER_CONTROL.modifyGold(UserState.getToken(), finalNum);
                        if (responseEntity.getCode() == 0){
                            //查询更新金钱
                            responseEntity = Controller.USER_CONTROL.getGold(UserState.getToken());
                            //查询成功
                            if (responseEntity.getCode() == 0){
                                MyDataPanel.this.money = Double.parseDouble(responseEntity.getData());
                                showMessage("充值成功");
                                updatePanel("moneyPanel");
                            }
                        } else {
                            showMessage("充值失败");
                        }
                    }
                });
                break;
            case "record":
                RecordDialog.recordDialog(FrameBase.frameBaseList.get(0),FrameBase.frameBaseList.get(0));
                break;
            default:
                try{
                    if ("edit".equals(e.getActionCommand().substring(0,4))){
                        singleThreadExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                ResponseEntity responseEntity = Controller.GOOD_CONTROL.getGoodInfo(
                                        Integer.parseInt(e.getActionCommand().substring(4)));
                                if (responseEntity.getCode() == 0){
                                    Good good = JSONObject.parseObject(responseEntity.getData(), Good.class);
                                    EditPage editPage = new EditPage("编辑商品",good);
                                    editPage.setVisible(true);
                                } else {
                                    showMessage("获取商品信息失败，无法编辑");
                                }
                            }
                        });
                    }
                    //商品展示界面
                    if ("page".equals(e.getActionCommand().substring(0, 4))){
                        singleThreadExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                ResponseEntity responseEntity = Controller.GOOD_CONTROL.getGoodInfo(
                                        Integer.parseInt(e.getActionCommand().substring(4))
                                );
                                if (responseEntity.getCode() == 0){
                                    Good good = JSONObject.parseObject(responseEntity.getData(), Good.class);
                                    GoodsPage goodsPage = new GoodsPage(good);
                                    goodsPage.setVisible(true);
                                }
                            }
                        });
                    }
                    if ("state".equals(e.getActionCommand().substring(0,5))){
                        singleThreadExecutor.execute(new Runnable() {
                            @Override
                            public void run() {
                                ResponseEntity responseEntity = Controller.GOOD_CONTROL.modifyStatus(
                                        UserState.getToken(), Integer.parseInt(e.getActionCommand().substring(5)));
                                if (responseEntity.getCode() == 0){
                                    getMyGoodList();
                                    PanelControl p = PanelControl.panels.get("GoodsPanel");
                                    if (p instanceof GoodsPanel){
                                        p.updatePanel("itemPanel");
                                    }
                                    if (Integer.parseInt(responseEntity.getData()) == 0){
                                        showMessage("商品下架成功");
                                    } else {
                                        showMessage("商品上架成功");
                                    }
                                }
                            }
                        });
                    }
                    if ("delete".equals(e.getActionCommand().substring(0,6))){
                        int c = JOptionPane.showConfirmDialog(MyDataPanel.this,
                                "确定删除","确认删除",JOptionPane.YES_NO_CANCEL_OPTION);
                        if (c == JOptionPane.YES_OPTION){
                            singleThreadExecutor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    ResponseEntity responseEntity = Controller.GOOD_CONTROL.deleteGood(
                                            UserState.getToken(), Integer.parseInt(e.getActionCommand().substring(6)));
                                    if (responseEntity.getCode() == 0){
                                        showMessage("删除成功");
                                        getMyGoodList();
                                    } else {
                                        showMessage("删除失败");
                                    }
                                }
                            });
                        }
                    }
                    if ("auction".equals(e.getActionCommand().substring(0,7))){
                        AuctionDialog.showAuctionDialog(FrameBase.frameBaseList.get(0),
                                FrameBase.frameBaseList.get(0),
                                Integer.parseInt(e.getActionCommand().substring(7)));
                    }
                } catch (Exception ignore){}
        }
    }


    /**
     * @Description 通过更新我的商品列表,更新myItems
     * @author 孔明浩
     * @Date 2020/4/5
     */
    public void getMyGoodList(){
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                myItems = Controller.STORE_CONTROL.getStoreGoods(UserState.getToken());
                ResponseEntity responseEntity = Controller.RECORD_CONTROL.getRecordOfUser(UserState.getToken());
                if (responseEntity.getCode() == 0){
                    boughtItems = JSONObject.parseArray(responseEntity.getData(), Record.class);
                }
                if (boughtItems == null){
                    boughtItems = new ArrayList<>();
                }
                updatePanel("myShopPanel");
                updatePanel("boughtPanel");
            }
        });
    }

    private void showMessage(String message){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(MyDataPanel.this,message);
            }
        });
    }
}
